import { asyncRoutes, constantRoutes } from '@/router'
import { getUserMenu } from "@/api/menu";
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
//
// hasPermission(['editor'],{path:,component,meta:{roles:['editor',']}}):boolean
//判断当前用户是否有权限访问这个路由
function hasPermission(roles, route) {
  //有route中有meta并且meta中有roles
  if (route.meta && route.meta.roles) {
    //判断当前用户的角色是否包含在meta中的角色中，如果包含就返回true，否则返回false
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    //没有meta或者meta中没有roles，那么就是所有人都可以访问
    return true
  }
}


//routers是所有的动态路由规则，roles是当前用户的角色
export function filterAsyncRoutes(routes) {
  const res = [];
  routes.forEach(async (route) => {
    const tmp = { ...route };
    if (tmp.component == "Layout") {
      tmp.component = Layout;
    } else if (tmp.component === "ParentView") {
      tmp.component = ParentView;
    } else {
      try {
        const module = require('@/views' + tmp.component + '.vue');
        tmp.component = module.default;
      } catch (error) {
        // 处理模块加载失败的情况
        console.log('无法发现组件：', error)
        tmp.component = () => import(`@/views/error/404.vue`);
      }
    }
    res.push(tmp);
    if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children);
    }
  });
  return res;
}

const state = {
  routes: [], //静态路由规则 + 当前路由可以访问的动态路由规则
}

//状态赋值
const mutations = {
  SET_ROUTES: (state, routes) => {
    state.routes = constantRoutes.concat(routes)
  }
}



const actions = {
  //generateRoutes计算生成需要权限访问的动态路由
  generateRoutes({ commit }) {
    return new Promise((resolve, reject) => {
      getUserMenu()
        .then(({ data, code }) => {
          console.log(data)
          if (code == 200) {
            const asyncRoutes = data;//动态路由信息
            const accessedRoutes = filterAsyncRoutes(asyncRoutes);
            console.log('dongtailiu', accessedRoutes)
            commit('SET_ROUTES', accessedRoutes);
            resolve(accessedRoutes);
          }

        })
        .catch((error) => {
          reject(error);
        });
    });
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
